import { Component } from "react";

import { Toast } from "antd-mobile";

import NavHeader from '../../components/NavHeader'

import styles from './index.module.css'

// import axios from 'axios'
import { API } from "../../utils/api";

// 导入BASE_URL
import { BASE_URL } from "../../utils/url"; 
import HouseItem from "../../components/HouseItem";

export default class Map extends Component {
  constructor(props) {
    super(props)

    this.state = {
      // 房源数据
      houseInfo: [],
      // 是否正在加载标识
      isLoading: true,
      // 小区房屋信息数据
      housesList: [],
      // 是否展示小区房屋信息数据标识
      showHouse: false,
    }
  }

  // 地图绘制
  renderMap(pos, label, scale) {
    // 创建地图实例
    var map = new window.BMapGL.Map("container")

    let scaleNum = 11
    switch (scale) {
      case 1:
        scaleNum = 11
        break
      case 2:
        scaleNum = 13
        break
      case 3: 
        scaleNum = 16
        break
      default:
        break
    }

    // 渲染第一级别的地图，地图中心点由地址解析器解析获得
    if (scale === 1) {
      //创建地址解析器实例
      var myGeo = new window.BMapGL.Geocoder();
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(label+'市', (point) => {
        if (point) {
          map.centerAndZoom(point, scaleNum);
        }
      })
    } else {
      map.centerAndZoom(pos, scaleNum);
    }

    this.state.houseInfo.map(item => {
      return this.renderOverlay(map, item, scale)
    })
    // 添加常用控件
    map.addControl(new window.BMapGL.ZoomControl())
    map.addControl(new window.BMapGL.ScaleControl())

    // 地图绑定移动事件
    map.addEventListener('movestart', () => {
      // 如果当前小区房源已处于展示状态，则移动地图会导致房源展示隐藏
      if (this.state.showHouse) {
        this.setState({
          showHouse: false
        })
      }
    })
  }

  // 绘制地图覆盖物
  renderOverlay(map, house, scale) {
    let point = {
      lat: house.coord.latitude,
      lng: house.coord.longitude
    }
    const opts = {
      position: point,
      // offset: new window.BMapGL.Size(30, -30)
    }

    const label = new window.BMapGL.Label('', opts)
    // 给label对象添加唯一标识
    label.id = house.value
    // 设置房源覆盖物内容
    label.setContent(`
      <div class="${scale < 3 ? styles.bubble : styles.bubble1}">
        <p class="${scale < 3 ? styles.name : styles.name1}">${house.label}</p>
        <p>${house.count}套</p>
      </div>
    `)

    //设置样式
    label.setStyle({
      color: '#fff',
      textAlign: 'center',
      cursor: 'pointer',
      border: '0px solid rgb(255, 0, 0)',
      fontSize: '12px',
      padding: '0px',
      lineHeight: '40px'
    })

    // 添加单击事件
    label.addEventListener('click', async (e) => {
      if (scale < 3) {
        map.clearOverlays()
        this.setState({
          isLoading: true
        })
        // 获取下一级房源数据
        await this.getHouseInfo(house.value)
        // 渲染下一级地图
        this.renderMap(point, house.label, scale + 1)
      } else {
        this.showHouseInfo(house.value, e, map)
      }
    })

    // 添加覆盖物到地图中
    map.addOverlay(label)
  }

  // 小区点击事件
  async showHouseInfo(houseId, e, map) {
    Toast.loading('Loading...', 30);
    let res = await API.get(`${BASE_URL}/houses?cityId=${houseId}`)
    Toast.hide()

    // 计算地图位移值
    let ver = (window.innerHeight - 430)/2 - 40 - e.target.domElement.offsetTop
    let hor = window.innerWidth/2 - e.target.domElement.offsetLeft

    // 将地图根据点击小区位置进行移动
    map.panBy(hor, ver)

    this.setState({
      housesList: res.data.body.list,
      showHouse: true,
    })
  }

  // 获取房源数据
  async getHouseInfo(areaId) {
    try {
      if (this.state.isLoading) {
        Toast.loading('数据加载中...', 0);
      }
      let res = await API.get(`${BASE_URL}/area/map?id=${areaId}`)
      Toast.hide()
      this.setState({
        houseInfo: res.data.body,
        isLoading: false
      })
    } catch(err) {
      Toast.hide()
      Toast.fail('发生错误：' + err, 2)
    }
  }

  async componentDidMount() {
    // 初始化地区信息
    if (localStorage.getItem('hkzf_city')!==null) {
      var { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
    } else {
      label = '北京'
      value = 'AREA|88cff55c-aaa4-e2e0'
    }
    // 获取房源信息并调用地图渲染函数
    await this.getHouseInfo(value)
    this.renderMap({}, label, 1)
  }

  render() {
    return (
      <div className={styles.map}>
        <NavHeader>
          地图找房
        </NavHeader>
        <div id="container" className={styles.container}></div>
        <div className={[styles.houseInfo, this.state.showHouse ? styles.show : '', this.state.moveHouse ? styles.move : ''].join(' ')} >
          <div className={styles.header} onClick={() => {console.log(1)}}>
            房屋列表
            <span className={styles.more}>更多房源</span>
          </div>
          {/* 渲染小区房源信息列表 */}
          {
            this.state.housesList.map((house, id) => {
              return <HouseItem house={house} key={id} ikey={house.value}/>
            })
          }
        </div>
      </div>
    );
  }
}
